# -*- coding: utf-8 -*-
import os
import wget
import time
import rospy
import json
import requests
import roslaunch
import signal 
import subprocess
from threading import Thread, Event
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from sensor_msgs.msg import BatteryState

class robotmap():
    def __init__(self):
        self.proc = subprocess.Popen("ls")
        
    def start(self):
        self.proc = subprocess.Popen(['roslaunch robot_navigation robot_slam_laser.launch'],shell=True, close_fds=True)
        data = {"method": "map.start", "code": "1", "msg": ""}
        return data

    def stop(self):
        os.system("pkill -f robot_slam_laser.launch")
        try:
            os.killpg(self.proc.pid, signal.SIGTERM)
        except OSError as e:
            print(repr(e))
        data = {"method": "map.stop", "code": "1", "msg": ""}
        return data

    def upload(self):
        rospy.loginfo("start upload map file")
        subprocess.Popen(['convert /home/jy/billiard/src/navigation/maps/map.pgm /home/jy/billiard/src/navigation/maps/map.png'],shell=True, close_fds=True)
        url = 'https://api.merchant.dev.richwin8.com/robot/clean'
        files = {
            # image或者file
            'image': ('/home/jy/billiard/src/navigation/maps/map.png', open('/home/jy/billiard/src/navigation/maps/map.png', 'rb'), 'image/jpeg')
            # 'image': ('/home/ros/onion/src/navigation/maps/map.png', open('map.png', 'rb'), 'image/jpeg')
        }
        data = {
            'method': 'upload',
            'seqnum': '866562',
            'image': 'map.png'
        }
        r = requests.post(url=url,data=data, files=files)
        rospy.loginfo(r.text)
        rjson = json.loads(r.text)
        rospy.loginfo(r.status_code)
        rospy.loginfo(rjson.get('data').get('url'))
        if r.status_code == 200:
            image_url = rjson.get('data').get('url')
        res = {"method": "map.upload", "url": image_url, "name": "map.png"}
        rospy.loginfo("res -->"+str(res))
        return res

    def download(self,url):
        file_path = '/home/jy/billiard/src/navigation/maps/'
        # file_path = '/home/ros/onion/src/navigation/maps/'
        wget.download(url, file_path)
        os.system("convert map.png map.pgm")
        data = {"method": "map.download_finished", "code": "1", "msg": ""}
        os.system("rm -f map.png")
        return data

    def space_arrange(self,home,count,tables):
        with open("space_arrange.json", "w") as f:
            arranges = [home, count, tables]
            json.dump(arranges, f)
        data = {"method": "map.space_arrange", "code": "1", "msg": ""}
        return data
